﻿using System;
using System.Windows.Controls;
using System.Windows.Input;


namespace LogicStudio.Framework.UI.Controles
{
    //This control is a textbox control where you can only write numbers
    public class NumericTextBox : TextBox
    {
        static bool _altGrIsPressed;

        /// <summary>
        /// When the control get an instance, add a suscription for KeyUp and KeyDown events
        /// </summary>
        public NumericTextBox()
            :base()
        {
            this.KeyUp += Numclient_KeyUp;
            this.KeyDown += Numclient_KeyDown;
        }

        /// <summary>
        /// Override OnApplyTemplate method
        /// </summary>
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
        }

        /// <summary>
        /// This method implement the logic when KeyUp event is raised
        /// </summary>
        /// <param name="sender">Object</param>
        /// <param name="e">Event Arguments</param>
        void Numclient_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Alt)
            {
                _altGrIsPressed = false;
            }

        }

        /// <summary>
        /// This method implement the logic when KeyDown event is raised. In this method is where the custom textbox allows only write numbers
        /// </summary>
        /// <param name="sender">Object Sender</param>
        /// <param name="e">Event Arguments</param>
        void Numclient_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Alt)
            {
                _altGrIsPressed = true;
            }

            if (Keyboard.Modifiers == ModifierKeys.Shift || _altGrIsPressed == true)
            {
                e.Handled = true;
            }

            if (e.Handled == false && (e.Key < Key.D0 || e.Key > Key.D9))
            {
                if (e.Key < Key.NumPad0 || e.Key > Key.NumPad9)
                {
                    if (e.Key != Key.Back)
                    {
                        e.Handled = true;
                    }
                }
            }
        }

    }
}
